"""
API场景组合测试工具 - 数据库模型
"""
from datetime import datetime
from app import db
import json

class ApiInfo(db.Model):
    """API信息表"""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    url = db.Column(db.String(500), nullable=False)
    method = db.Column(db.String(10), nullable=False)
    headers = db.Column(db.Text)  # 存储为JSON字符串
    body_template = db.Column(db.Text)  # 请求体模板，支持变量占位符
    description = db.Column(db.Text)
    module = db.Column(db.String(50))  # 所属模块
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'url': self.url,
            'method': self.method,
            'headers': json.loads(self.headers) if self.headers else {},
            'body_template': self.body_template,
            'description': self.description,
            'module': self.module,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }

class Scene(db.Model):
    """场景表"""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    script = db.Column(db.Text)  # 场景脚本，支持变量、条件、循环等
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 场景步骤，一对多关系
    steps = db.relationship('SceneStep', backref='scene', lazy=True, cascade='all, delete-orphan')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'script': self.script,
            'steps': [step.to_dict() for step in self.steps],
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }

class SceneStep(db.Model):
    """场景步骤表"""
    id = db.Column(db.Integer, primary_key=True)
    scene_id = db.Column(db.Integer, db.ForeignKey('scene.id'), nullable=False)
    name = db.Column(db.String(100))
    step_type = db.Column(db.String(20), nullable=False)  # API, SCENE, SCRIPT
    api_id = db.Column(db.Integer, db.ForeignKey('api_info.id'))
    referenced_scene_id = db.Column(db.Integer, db.ForeignKey('scene.id'))
    script_content = db.Column(db.Text)  # 脚本内容
    order = db.Column(db.Integer, nullable=False)  # 执行顺序
    params = db.Column(db.Text)  # 参数配置，JSON格式
    
    # 关联的API
    api = db.relationship('ApiInfo', foreign_keys=[api_id])
    # 引用的场景
    referenced_scene = db.relationship('Scene', foreign_keys=[referenced_scene_id])
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'step_type': self.step_type,
            'api_id': self.api_id,
            'referenced_scene_id': self.referenced_scene_id,
            'script_content': self.script_content,
            'order': self.order,
            'params': json.loads(self.params) if self.params else {}
        }

class Environment(db.Model):
    """环境配置表"""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    base_url = db.Column(db.String(200))
    description = db.Column(db.Text)
    config = db.Column(db.Text)  # 环境配置，JSON格式
    auth_config = db.Column(db.Text)  # 认证配置，JSON格式
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'base_url': self.base_url,
            'description': self.description,
            'config': json.loads(self.config) if self.config else {},
            'auth_config': json.loads(self.auth_config) if self.auth_config else {},
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }

class ExecutionRecord(db.Model):
    """执行记录表"""
    id = db.Column(db.Integer, primary_key=True)
    scene_id = db.Column(db.Integer, db.ForeignKey('scene.id'), nullable=False)
    environment_id = db.Column(db.Integer, db.ForeignKey('environment.id'), nullable=False)
    template_data_id = db.Column(db.String(50))  # 模板数据ID
    status = db.Column(db.String(20))  # SUCCESS, FAILED, RUNNING
    start_time = db.Column(db.DateTime, default=datetime.now)
    end_time = db.Column(db.DateTime)
    result = db.Column(db.Text)  # 执行结果，JSON格式
    
    # 关联的场景和环境
    scene = db.relationship('Scene')
    environment = db.relationship('Environment')
    
    # 执行步骤记录，一对多关系
    step_records = db.relationship('StepExecutionRecord', backref='execution', lazy=True, cascade='all, delete-orphan')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'scene_id': self.scene_id,
            'environment_id': self.environment_id,
            'template_data_id': self.template_data_id,
            'status': self.status,
            'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'end_time': self.end_time.strftime('%Y-%m-%d %H:%M:%S') if self.end_time else None,
            'result': json.loads(self.result) if self.result else {},
            'step_records': [record.to_dict() for record in self.step_records]
        }

class StepExecutionRecord(db.Model):
    """步骤执行记录表"""
    id = db.Column(db.Integer, primary_key=True)
    execution_id = db.Column(db.Integer, db.ForeignKey('execution_record.id'), nullable=False)
    step_id = db.Column(db.Integer)  # 对应SceneStep的ID
    step_name = db.Column(db.String(100))
    step_type = db.Column(db.String(20))
    status = db.Column(db.String(20))  # SUCCESS, FAILED
    start_time = db.Column(db.DateTime, default=datetime.now)
    end_time = db.Column(db.DateTime)
    request = db.Column(db.Text)  # 请求内容，JSON格式
    response = db.Column(db.Text)  # 响应内容，JSON格式
    error = db.Column(db.Text)  # 错误信息
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'execution_id': self.execution_id,
            'step_id': self.step_id,
            'step_name': self.step_name,
            'step_type': self.step_type,
            'status': self.status,
            'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'end_time': self.end_time.strftime('%Y-%m-%d %H:%M:%S') if self.end_time else None,
            'request': json.loads(self.request) if self.request else {},
            'response': json.loads(self.response) if self.response else {},
            'error': self.error
        }

class AuthCache(db.Model):
    """认证缓存表"""
    id = db.Column(db.Integer, primary_key=True)
    environment_id = db.Column(db.Integer, db.ForeignKey('environment.id'), nullable=False)
    auth_data = db.Column(db.Text)  # 认证数据，JSON格式
    created_at = db.Column(db.DateTime, default=datetime.now)
    expires_at = db.Column(db.DateTime)  # 过期时间
    is_valid = db.Column(db.Boolean, default=True)  # 是否有效
    
    # 关联的环境
    environment = db.relationship('Environment')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'environment_id': self.environment_id,
            'auth_data': json.loads(self.auth_data) if self.auth_data else {},
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'expires_at': self.expires_at.strftime('%Y-%m-%d %H:%M:%S') if self.expires_at else None,
            'is_valid': self.is_valid
        }